﻿using BootstrapBlazor.Components;
using BPM.Web.Shared.Data;
using BPM.Web.Shared.Dependencies;
using BPM.Web.Shared.Extensions;
namespace BPM.Web.Shared.Service;

[Scoped(typeof(ISysUserService))]
public class SysUserService : BaseService, ISysUserService
{
    private readonly IUserClient _client;
    public SysUserService(IUserClient userClient, ToastService toast) : base(toast)
        => _client = userClient;

    public Task<QueryData<UserOutput>> PageAsync(UserPageInput input)
        => QueryAsync(_client.PageAsync(input));

    public Task<bool> AddAsync(UserOutput input)
        => ExecuteAsync(_client.AddAsync(input.Adapt<AddUserInput>()));

    public Task<bool> DeleteAsync(IEnumerable<UserOutput> input)
        => DeleteAsync(input.Adapts<UserOutput, DeleteUserInput>().Select(x => _client.DeleteAsync(x)));

    public Task<bool> EditAsync(UserOutput input)
        => ExecuteAsync(_client.EditAsync(input.Adapt<UpdateUserInput>()));

    public Task<UserOutput?> DetailAsync(QueryUserInput input)
        => QueryAsync(_client.DetailAsync(input));

    public async Task<IEnumerable<SelectedItem>> SelectorAsync(UserSelectorInput input)
    {
        var result = new List<SelectedItem>();
        var data = await QueryAsync<List<UserOutput>>(_client.SelectorAsync(input));
        if (data.HasValue())
        {
            data!.ForEach(x => result.Add(new(x.Id.ToString(), x.Name ?? x.Account ?? "匿名")));
        }
        return result;
    }

    public Task<bool> ResetPwdAsync(UserOutput input)
        => ExecuteAsync(_client.ResetPwdAsync(input.Adapt<QueryUserInput>()));

    public Task<bool> UpdateAvatarAsync(long id)
        => ExecuteAsync(_client.UpdateAvatarAsync(new() { Id = id }));
    public async Task<List<RoleOutput>> OwnRoleAsync(IEnumerable<RoleOutput>? items, UserOutput input)
    {
        if (items.HasValue())
        {
            var ids = await QueryAsync(_client.OwnRoleAsync(input.Adapt<QueryUserInput>()));
            if (ids.HasValue())
            {
                return items!.Where(x => ids!.Contains(x.Id) == true).ToList();
            }
        }

        return new();
    }

    public async Task OwnDataAsync(IEnumerable<TreeItem>? items, UserOutput input)
    {
        var ids = await QueryAsync(_client.OwnDataAsync(input.Adapt<QueryUserInput>()));
        items?.CascadeSetCheck(ids);
    }

    public Task<bool> GrantRoleAsync(IEnumerable<long>? ids, UserOutput input)
        => ids.HasValue().TrueFor(
                () => ExecuteAsync(_client.GrantRoleAsync(input
                    .Adapt<UpdateUserRoleDataInput>()
                    .SetValue(x => x.GrantRoleIdList, ids))));

    public Task<bool> GrantDataAsync(IEnumerable<long>? ids, UserOutput input)
        => ids.HasValue().TrueFor(
                () => ExecuteAsync(_client.GrantDataAsync(input
                    .Adapt<UpdateUserRoleDataInput>()
                    .SetValue(x => x.GrantOrgIdList, ids))));


}

